#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
from Queue import Queue

'''
Created on Sep 27, 2012

@author: join
'''
import time
import urllib2
import threading
import datetime

queue = Queue()
init_query_awardcode = True
init_run_method = True

def run_method(lotterycode):
    time.sleep(3)
    while True:
        now_hour = int(datetime.datetime.now().strftime("%H"))
        if lotterycode=='20' and (now_hour<9 or now_hour>23): #9点之前，23点之后不做期次更新
            time.sleep(5)
            continue
        try:
            req = urllib2.Request('http://localhost:8000/query_periodid/%s'%lotterycode)
            response=urllib2.urlopen(req)
            info=response.read()
            if info != 'error':
                info_dict = eval(info)
                #获取开奖号码，奖池信息
                time.sleep(int(info_dict['seconds']))
                req2 = urllib2.Request('http://localhost:8000/query_awardcode/%s/%s' % (lotterycode,info_dict['periodid']))
                response2 = urllib2.urlopen(req2)
                response2 =response2.read()
                if response2!='ok':
                    que_msg = '%s#%s'%(lotterycode,info_dict['periodid'])
                    queue.put(que_msg)
            time.sleep(1)
        except Exception as e:
            print 'error:',e
            time.sleep(1)

def query_awardcode():
    time.sleep(3)
    while True:
        if queue.qsize()<1:
            pass
        else:
            msg = queue.get()
            lotterycode,periodid = msg.split('#')
            req2 = urllib2.Request('http://localhost:8000/query_awardcode/%s/%s' % (lotterycode,periodid))
            response2 = urllib2.urlopen(req2)
            response2 =response2.read()
            print '###########response2',response2
            if response2 != 'ok':
                print 'put into queue again.',msg
                que_msg = '%s#%s'%(lotterycode,periodid)
                queue.put(que_msg)
        time.sleep(1)

def init():
    ssc_thread=threading.Thread(target=run_method, args=('20',)) #时时彩线程
    ssc_thread.start()
    ssq_thread=threading.Thread(target=run_method, args=('01',)) #双色球线程
    ssq_thread.start()
    sevencolor_thread = threading.Thread(target=run_method, args=('07',)) #七乐彩线程
    sevencolor_thread.start()
    threeD_thread = threading.Thread(target=run_method, args=('05',)) #福彩3D线程
    threeD_thread.start()
    fifteenFive_thread = threading.Thread(target=run_method, args=('15',)) #15选5线程
    fifteenFive_thread.start()
    sixOne_thread = threading.Thread(target=run_method, args=('06',)) #福彩3D线程
    sixOne_thread.start()
    #查询开奖号码
    query_thread = threading.Thread(target=query_awardcode)
    query_thread.start()

if __name__ == '__main__':
    pass
